<template>
    <el-dialog :title="$t('tool.modelManage.preview')" :visible.sync="dialogVisible" append-to-body width="800px" @opened="initEditor">
        <div class="monaco-dialog-editor-container">
            <div class="container-header">
                <el-button class="jsonschema-btn" @click="handleDynamicGeneration">
                    <span role="img" class="appIcon">
                        <svg-icon icon-class="refresh-page" width="16" height="16" />
                    </span>
                    {{ $t("tool.modelManage.dynamicGeneration") }}
                </el-button>
            </div>
            <div ref="previewContainer" :class="['monaco-dialog-editor']"></div>
        </div>
    </el-dialog>
</template>

<script>
import * as monaco from 'monaco-editor';
import jsf from 'json-schema-faker';
import { da, faker } from '@faker-js/faker';
import jsonSchemaToolHandle from "@/utils/jsonSchema-tool.js";
export default {
    props: {
        currentJsonSchemaData: String, // 当前点击的jsonSchema数据
        language: { type: String, default: 'json' },
        theme: { type: String, default: 'vs-dark' }
    },
    data() {
        return {
            dialogVisible: false,
            editor: null,
            jsonSchema: {}, // 当前模型的所有jsonSchema数据
            resolveRefsJsonSchema: {}, // 解析后的jsonSchema数据
            customTheme: {
                "dark": {
                    base: 'vs-dark',
                    inherit: true,
                    rules: [],
                    colors: {
                        'editor.background': '#191a23',
                    }
                },
                "darkblue": {
                    base: 'vs-dark',
                    inherit: true,
                    rules: [],
                    colors: {
                        'editor.background': '#22272e',
                    }
                },
                "grey": {
                    base: 'vs-dark',
                    inherit: true,
                    rules: [],
                    colors: {
                        'editor.background': '#242424',
                    }
                },
                "light": {
                    base: 'vs',
                    inherit: true,
                    rules: [],
                    colors: {
                        'editor.background': '#ffffff',
                    }
                },
                "lightbrown": {
                    base: 'vs',
                    inherit: true,
                    rules: [],
                    colors: {
                        'editor.background': '#f9f4e7',
                    }
                },

            }
        };
    },
    created() {
        this.jsonSchemaTool = new jsonSchemaToolHandle(this);
        jsf.option({
            alwaysFakeOptionals: true,
            fillProperties: false,
        })
    },
    methods: {
        openDialog() {
            this.dialogVisible = true;
            // 销毁旧实例
            if (this.editor) this.editor.dispose();
        },
        initEditor() {
            // 获取主题
            let { backKeyWord, themeConfig } = this.getSystemThemeStyle()
            // 注册主题
            monaco.editor.defineTheme(backKeyWord, themeConfig);
            // 应用主题
            monaco.editor.setTheme(backKeyWord);
            // 解析带有引用的数据
            this.modelDataList = JSON.parse(localStorage.getItem("modelDataList"));
            this.jsonSchema = this.modelDataList ? JSON.parse(localStorage.getItem("modelDataList")).concat(JSON.parse(localStorage.getItem("globalTreeData"))) : JSON.parse(localStorage.getItem("globalTreeData"));
            this.resolveRefsJsonSchema = this.jsonSchemaTool.resolveRefs(JSON.parse(this.currentJsonSchemaData), this.jsonSchema);
            // 删除临时的属性
            this.resolveRefsJsonSchema = this.jsonSchemaTool.removeTmpProperties(this.resolveRefsJsonSchema)

            jsf.extend('faker', () => faker);
            const data = jsf.generate(this.resolveRefsJsonSchema);
            this.editor = monaco.editor.create(this.$refs.previewContainer, {
                value: JSON.stringify(data, null, 8) || '',
                language: this.language,
                // theme: this.theme,
                wordWrap: 'off',
                renderLineHighlight: 'none',
                minimap: { enabled: false },
                readOnly: true,
                fontSize: 12,
                lineHeight: 16,
                automaticLayout: true  // 关键：启用自动布局
            });
            // 内容同步
            this.editor.onDidChangeModelContent(() => {
            });
            // 窗口尺寸监听（需配合CSS）
            new ResizeObserver(() => this.editor.layout()).observe(this.$refs.previewContainer);
        },
        // 处理动态生成
        handleDynamicGeneration() {
            const data = jsf.generate(this.resolveRefsJsonSchema);
            this.editor.setValue(JSON.stringify(data, null, 8))
        },
        // 获取当前系统主题样式
        getSystemThemeStyle() {
            let themeConfig = localStorage.getItem("themeConfig")
            let backKeyWord = themeConfig.slice(0, themeConfig.search(/[A-Z]/));
            return {
                backKeyWord,
                themeConfig: this.customTheme[backKeyWord]
            }
        }
    },
    beforeDestroy() {
        this.editor?.dispose();
    }
};
</script>

<style scoped>
.monaco-dialog-editor {
    /* 视窗高度自适应 */
    /* border: 1px solid #dcdfe6; */
    height: 350px;
    border-radius: 4px;
}

.monaco-dialog-editor-container {
    border: 1px solid var(--ui-border-color-base);
    border-radius: 8px;
}

.container-header {
    display: flex;
    justify-content: center;
    height: 38px;
    border-bottom: 1px solid var(--ui-border-color-base);
    padding: 5px 0px 5px 0px;
}
</style>